<?php

namespace App\Admin\Form\Field;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Checkbox extends Select
{
    protected $default = [0];

    /**
     * 多对多关系中的otherKey字段名
     *
     * @var string
     */
    protected $otherKey;

    /**
     * 获取该字段多对多关联中的otherKey字段名
     *
     * @return string
     * @throws \Exception
     */
    protected function getOtherKey()
    {
        if ($this->otherKey) {
            return $this->otherKey;
        }

        if (
            method_exists($this->form->model(), $this->column) &&
            ($relation = $this->form->model()->{$this->column}()) instanceof BelongsToMany
        ) {
            /** @var BelongsToMany $relation */
            return $this->otherKey = $relation->getRelatedPivotKeyName();
        }

        throw new \Exception('该字段必须是 BelongsToMany 关联');
    }

    public function fill($data)
    {
        $relations = array_get($data, $this->column);

        if (is_string($relations)) {
            $this->value = explode(',', $relations);
        }

        if (is_array($relations)) {
            if (is_string(current($relations))) {
                $this->value = $relations;
            } else {
                foreach ($relations as $r) {
                    $this->value[] = array_get($r, "pivot.{$this->getOtherKey()}");
                }
            }
        }
    }

    public function setOriginal($data)
    {
        $relations = array_get($data, $this->column);

        if (is_string($relations)) {
            $this->original = explode(',', $relations);
        }

        if (is_array($relations)) {
            if (is_string(current($relations))) {
                $this->original = $relations;
            } else {
                foreach ($relations as $r) {
                    $this->original[] = array_get($r, "pivot.{$this->getOtherKey()}");
                }
            }
        }
    }

    /**
     * 存储组件的值之前的回调函数
     *
     * @param array $value
     * @return array
     */
    public function prepare(array $value)
    {
        return array_filter($value);
    }
}